/**
 * Copyright 2018 jianggujin (www.jianggujin.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jianggujin.codec;

import java.io.InputStream;
import java.io.OutputStream;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import com.jianggujin.codec.util.JCipherInputStream;
import com.jianggujin.codec.util.JCipherOutputStream;
import com.jianggujin.codec.util.JCodecException;
import com.jianggujin.codec.util.JCodecUtils;

/**
 * 3DES（或称为Triple DES）是三重数据加密算法（TDEA，Triple Data Encryption
 * Algorithm）块密码的通称。它相当于是对每个数据块应用三次DES加密算法
 * 
 * @author jianggujin
 *
 */
public class JTripleDES {

   /**
    * 算法
    * 
    * @author jianggujin
    *
    */
   public static enum JTripleAlgorithm {

      AES, DES, DESede;

      public String getName() {
         return this.name();
      }
   }

   /**
    * 工作模式
    * 
    * @author jianggujin
    *
    */
   public static enum JWorkingMode {

      /**
       * 该模式不能使用向量
       */
      ECB, CBC, CFB, OFB, CTR;

      public String getName() {
         return this.name();
      }
   }

   /**
    * 填充方式
    * 
    * @author jianggujin
    *
    */
   public static enum JPadding {

      NoPadding, PKCS5Padding;

      public String getName() {
         return this.name();
      }
   }

   /**
    * 初始化密钥
    * 
    * @param algorithm
    * @return
    */
   public static SecretKey initKey(JTripleAlgorithm algorithm) {
      return initKey(algorithm.getName());
   }

   /**
    * 初始化密钥
    * 
    * @param algorithm
    * @return
    */
   public static SecretKey initKey(String algorithm) {
      return JCodecUtils.initKey(algorithm);
   }

   /**
    * 初始化密钥
    * 
    * @param algorithm
    * @return
    */
   public static byte[] initEncodedKey(JTripleAlgorithm algorithm) {
      return initEncodedKey(algorithm.getName());
   }

   /**
    * 初始化密钥
    * 
    * @param algorithm
    * @return
    */
   public static byte[] initEncodedKey(String algorithm) {
      return initKey(algorithm).getEncoded();
   }

   /**
    * 初始化向量
    * 
    * @param algorithm
    * @param workingMode
    * @param padding
    * @return
    */
   public static byte[] initIv(JTripleAlgorithm algorithm, JWorkingMode workingMode, JPadding padding) {
      return initIv(algorithm.getName(), workingMode.getName(), padding.getName());
   }

   /**
    * 初始化向量
    * 
    * @param algorithm
    * @param workingMode
    * @param padding
    * @return
    */
   public static byte[] initIv(String algorithm, String workingMode, String padding) {
      try {
         String fullAlg = algorithm + "/" + workingMode + "/" + padding;
         Cipher cipher = Cipher.getInstance(fullAlg);
         int blockSize = cipher.getBlockSize();
         byte[] iv = new byte[blockSize];
         for (int i = 0; i < blockSize; i++) {
            iv[i] = 0;
         }
         return iv;
      } catch (Exception e) {
         throw new JCodecException(e);
      }
   }

   /**
    * 加密
    * 
    * @param data
    * @param key
    * @param algorithm
    * @param workingMode
    * @param padding
    * @return
    */
   public static byte[] encrypt(byte[] data, byte[] key, JTripleAlgorithm algorithm, JWorkingMode workingMode,
         JPadding padding) {
      return encrypt(data, key, algorithm.getName(), workingMode.getName(), padding.getName());
   }

   /**
    * 加密
    * 
    * @param data
    * @param key
    * @param algorithm
    * @param workingMode
    * @param padding
    * @return
    */
   public static byte[] encrypt(byte[] data, byte[] key, String algorithm, String workingMode, String padding) {
      return encrypt(data, key, algorithm, workingMode, padding, null);
   }

   /**
    * 加密
    * 
    * @param data
    * @param secretKey
    * @param workingMode
    * @param padding
    * @return
    */
   public static byte[] encrypt(byte[] data, SecretKey secretKey, JWorkingMode workingMode, JPadding padding) {
      return encrypt(data, secretKey, workingMode.getName(), padding.getName());
   }

   /**
    * 加密
    * 
    * @param data
    * @param secretKey
    * @param workingMode
    * @param padding
    * @return
    */
   public static byte[] encrypt(byte[] data, SecretKey secretKey, String workingMode, String padding) {
      return encrypt(data, secretKey, workingMode, padding, null);
   }

   /**
    * 加密
    * 
    * @param data
    * @param key
    * @param algorithm
    * @param workingMode
    * @param padding
    * @param iv
    *           为null时则使用默认向量
    * @return
    */
   public static byte[] encrypt(byte[] data, byte[] key, JTripleAlgorithm algorithm, JWorkingMode workingMode,
         JPadding padding, byte[] iv) {
      return encrypt(data, key, algorithm.getName(), workingMode.getName(), padding.getName(), iv);
   }

   /**
    * 加密
    * 
    * @param data
    * @param key
    * @param algorithm
    * @param workingMode
    * @param padding
    * @param iv
    *           为null时则使用默认向量
    * @return
    */
   public static byte[] encrypt(byte[] data, byte[] key, String algorithm, String workingMode, String padding,
         byte[] iv) {
      // 数据加密
      Cipher cipher = getCipher(key, algorithm, workingMode, padding, iv, Cipher.ENCRYPT_MODE);
      return JCodecUtils.doFinal(data, cipher);
   }

   /**
    * 加密
    * 
    * @param data
    * @param secretKey
    * @param workingMode
    * @param padding
    * @param iv
    * @return
    */
   public static byte[] encrypt(byte[] data, SecretKey secretKey, JWorkingMode workingMode, JPadding padding,
         byte[] iv) {
      return encrypt(data, secretKey, workingMode.getName(), padding.getName(), iv);
   }

   /**
    * 加密
    * 
    * @param data
    * @param secretKey
    * @param workingMode
    * @param padding
    * @param iv
    * @return
    */
   public static byte[] encrypt(byte[] data, SecretKey secretKey, String workingMode, String padding, byte[] iv) {
      // 数据加密
      Cipher cipher = getCipher(secretKey, workingMode, padding, iv, Cipher.ENCRYPT_MODE);
      return JCodecUtils.doFinal(data, cipher);
   }

   public static OutputStream wrap(OutputStream out, byte[] key, JTripleAlgorithm algorithm, JWorkingMode workingMode,
         JPadding padding) {
      return wrap(out, key, algorithm.getName(), workingMode.getName(), padding.getName());
   }

   public static OutputStream wrap(OutputStream out, byte[] key, String algorithm, String workingMode, String padding) {
      return wrap(out, key, algorithm, workingMode, padding, null);
   }

   public static OutputStream wrap(OutputStream out, SecretKey secretKey, JWorkingMode workingMode, JPadding padding) {
      return wrap(out, secretKey, workingMode.getName(), padding.getName());
   }

   public static OutputStream wrap(OutputStream out, SecretKey secretKey, String workingMode, String padding) {
      return wrap(out, secretKey, workingMode, padding, null);
   }

   public static OutputStream wrap(OutputStream out, byte[] key, JTripleAlgorithm algorithm, JWorkingMode workingMode,
         JPadding padding, byte[] iv) {
      return wrap(out, key, algorithm.getName(), workingMode.getName(), padding.getName());
   }

   public static OutputStream wrap(OutputStream out, byte[] key, String algorithm, String workingMode, String padding,
         byte[] iv) {
      Cipher cipher = getCipher(key, algorithm, workingMode, padding, iv, Cipher.ENCRYPT_MODE);
      return new JCipherOutputStream(cipher, out);
   }

   public static OutputStream wrap(OutputStream out, SecretKey secretKey, JWorkingMode workingMode, JPadding padding,
         byte[] iv) {
      return wrap(out, secretKey, workingMode.getName(), padding.getName());
   }

   public static OutputStream wrap(OutputStream out, SecretKey secretKey, String workingMode, String padding,
         byte[] iv) {
      Cipher cipher = getCipher(secretKey, workingMode, padding, iv, Cipher.ENCRYPT_MODE);
      return new JCipherOutputStream(cipher, out);
   }

   /**
    * 解密
    * 
    * @param data
    * @param key
    * @param algorithm
    * @param workingMode
    * @param padding
    * @return
    */
   public static byte[] decrypt(byte[] data, byte[] key, JTripleAlgorithm algorithm, JWorkingMode workingMode,
         JPadding padding) {
      return decrypt(data, key, algorithm.getName(), workingMode.getName(), padding.getName());
   }

   /**
    * 解密
    * 
    * @param data
    * @param key
    * @param algorithm
    * @param workingMode
    * @param padding
    * @return
    */
   public static byte[] decrypt(byte[] data, byte[] key, String algorithm, String workingMode, String padding) {
      return decrypt(data, key, algorithm, workingMode, padding, null);
   }

   /**
    * 解密
    * 
    * @param data
    * @param secretKey
    * @param workingMode
    * @param padding
    * @return
    */
   public static byte[] decrypt(byte[] data, SecretKey secretKey, JWorkingMode workingMode, JPadding padding) {
      return decrypt(data, secretKey, workingMode.getName(), padding.getName());
   }

   /**
    * 解密
    * 
    * @param data
    * @param secretKey
    * @param workingMode
    * @param padding
    * @return
    */
   public static byte[] decrypt(byte[] data, SecretKey secretKey, String workingMode, String padding) {
      return decrypt(data, secretKey, workingMode, padding, null);
   }

   /**
    * 解密
    * 
    * @param data
    * @param key
    * @param algorithm
    * @param workingMode
    * @param padding
    * @param iv
    *           为null时则使用默认向量
    * @return
    */
   public static byte[] decrypt(byte[] data, byte[] key, JTripleAlgorithm algorithm, JWorkingMode workingMode,
         JPadding padding, byte[] iv) {
      return decrypt(data, key, algorithm.getName(), workingMode.getName(), padding.getName());
   }

   /**
    * 解密
    * 
    * @param data
    * @param key
    * @param algorithm
    * @param workingMode
    * @param padding
    * @param iv
    *           为null时则使用默认向量
    * @return
    */
   public static byte[] decrypt(byte[] data, byte[] key, String algorithm, String workingMode, String padding,
         byte[] iv) {
      Cipher cipher = getCipher(key, algorithm, workingMode, padding, iv, Cipher.DECRYPT_MODE);
      return JCodecUtils.doFinal(data, cipher);
   }

   /**
    * 解密
    * 
    * @param data
    * @param secretKey
    * @param workingMode
    * @param padding
    * @param iv
    * @return
    */
   public static byte[] decrypt(byte[] data, SecretKey secretKey, JWorkingMode workingMode, JPadding padding,
         byte[] iv) {
      return decrypt(data, secretKey, workingMode.getName(), padding.getName(), iv);
   }

   /**
    * 解密
    * 
    * @param data
    * @param secretKey
    * @param workingMode
    * @param padding
    * @param iv
    * @return
    */
   public static byte[] decrypt(byte[] data, SecretKey secretKey, String workingMode, String padding, byte[] iv) {
      // 数据解密
      Cipher cipher = getCipher(secretKey, workingMode, padding, iv, Cipher.DECRYPT_MODE);
      return JCodecUtils.doFinal(data, cipher);
   }

   public static InputStream wrap(InputStream in, byte[] key, JTripleAlgorithm algorithm, JWorkingMode workingMode,
         JPadding padding) {
      return wrap(in, key, algorithm.getName(), workingMode.getName(), padding.getName());
   }

   public static InputStream wrap(InputStream in, byte[] key, String algorithm, String workingMode, String padding) {
      return wrap(in, key, algorithm, workingMode, padding, null);
   }

   public static InputStream wrap(InputStream in, SecretKey secretKey, JWorkingMode workingMode, JPadding padding) {
      return wrap(in, secretKey, workingMode.getName(), padding.getName());
   }

   public static InputStream wrap(InputStream in, SecretKey secretKey, String workingMode, String padding) {
      return wrap(in, secretKey, workingMode, padding, null);
   }

   public static InputStream wrap(InputStream in, byte[] key, JTripleAlgorithm algorithm, JWorkingMode workingMode,
         JPadding padding, byte[] iv) {
      return wrap(in, key, algorithm.getName(), workingMode.getName(), padding.getName(), iv);
   }

   public static InputStream wrap(InputStream in, byte[] key, String algorithm, String workingMode, String padding,
         byte[] iv) {
      Cipher cipher = getCipher(key, algorithm, workingMode, padding, iv, Cipher.DECRYPT_MODE);
      return new JCipherInputStream(cipher, in);
   }

   public static InputStream wrap(InputStream in, SecretKey secretKey, JWorkingMode workingMode, JPadding padding,
         byte[] iv) {
      return wrap(in, secretKey, workingMode.getName(), padding.getName(), iv);
   }

   public static InputStream wrap(InputStream in, SecretKey secretKey, String workingMode, String padding, byte[] iv) {
      Cipher cipher = getCipher(secretKey, workingMode, padding, iv, Cipher.DECRYPT_MODE);
      return new JCipherInputStream(cipher, in);
   }

   public static Cipher getCipher(byte[] key, JTripleAlgorithm algorithm, JWorkingMode workingMode, JPadding padding,
         byte[] iv, int opmode) {
      return getCipher(key, algorithm.getName(), workingMode.getName(), padding.getName(), iv, opmode);
   }

   public static Cipher getCipher(byte[] key, String algorithm, String workingMode, String padding, byte[] iv,
         int opmode) {
      SecretKey secretKey = getSecretKey(key, algorithm);
      return getCipher(secretKey, workingMode, padding, iv, opmode);
   }

   public static Cipher getCipher(byte[] key, JTripleAlgorithm algorithm, JWorkingMode workingMode, JPadding padding,
         int opmode) {
      return getCipher(key, algorithm.getName(), workingMode.getName(), padding.getName(), opmode);
   }

   public static Cipher getCipher(byte[] key, String algorithm, String workingMode, String padding, int opmode) {
      return getCipher(key, algorithm, workingMode, padding, null, opmode);
   }

   public static Cipher getCipher(SecretKey secretKey, JWorkingMode workingMode, JPadding padding, int opmode) {
      return getCipher(secretKey, workingMode.getName(), padding.getName(), opmode);
   }

   public static Cipher getCipher(SecretKey secretKey, String workingMode, String padding, int opmode) {
      return getCipher(secretKey, workingMode, padding, null, opmode);
   }

   public static Cipher getCipher(SecretKey secretKey, JWorkingMode workingMode, JPadding padding, byte[] iv,
         int opmode) {
      return getCipher(secretKey, workingMode.getName(), padding.getName(), iv, opmode);
   }

   public static Cipher getCipher(SecretKey secretKey, String workingMode, String padding, byte[] iv, int opmode) {
      JCodecUtils.checkOpMode(opmode);
      try {
         String fullAlg = secretKey.getAlgorithm() + "/" + workingMode + "/" + padding;
         Cipher cipher = Cipher.getInstance(fullAlg);
         if (!JWorkingMode.ECB.getName().equalsIgnoreCase(workingMode)) {
            if (iv == null) {
               int blockSize = cipher.getBlockSize();
               iv = new byte[blockSize];
               for (int i = 0; i < blockSize; i++) {
                  iv[i] = 0;
               }
            }
            IvParameterSpec ivSpec = new IvParameterSpec(iv);
            cipher.init(opmode, secretKey, ivSpec);
         } else {
            cipher.init(opmode, secretKey);
         }
         return cipher;
      } catch (Exception e) {
         throw new JCodecException(e);
      }
   }

   /**
    * 获得密钥
    * 
    * @param key
    * @param algorithm
    * @return
    */
   public static SecretKey getSecretKey(byte[] key, JTripleAlgorithm algorithm) {
      return getSecretKey(key, algorithm.getName());
   }

   /**
    * 获得密钥
    * 
    * @param key
    * @param algorithm
    * @return
    */
   public static SecretKey getSecretKey(byte[] key, String algorithm) {
      try {
         SecretKey secretKey = new SecretKeySpec(key, algorithm);
         return secretKey;
      } catch (Exception e) {
         throw new JCodecException(e);
      }
   }
}
